﻿using System;
using System.Linq;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Xml.Highlightings;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Xml;
using JetBrains.ReSharper.Psi.Xml.Tree;
using JetBrains.Util;
using SPCAFContrib.ReSharper.Common;
using SPCAFContrib.ReSharper.Common.Attributes;
using SPCAFContrib.ReSharper.Common.Extensions;
using SPCAFContrib.ReSharper.Common.XmlAnalysis;
using SPCAFContrib.ReSharper.Consts;
using SPCAFContrib.ReSharper.Inspection.Xml.SPCAF;

[assembly: RegisterConfigurableSeverity(SPC016401Highlighting.CheckId,
  null,
  Consts.SPCAF_CORRECTNESS_GROUP,
  SPC016401Highlighting.CheckId + ": " + SPC016401Highlighting.Message,
  "WebPart should contain a title which is visible to the user in SharePoint.",
  Severity.ERROR,
  false, Internal = false)]

namespace SPCAFContrib.ReSharper.Inspection.Xml.SPCAF
{
    [Applicability(
        IDEProjectType.SP2010FarmSolution |
        IDEProjectType.SPSandbox |
        IDEProjectType.SP2013FarmSolution)]
    public class DeclareTitleInWebPartDefinition : XmlTagProblemAnalyzer
    {
        public override void Run(IXmlTag element, IHighlightingConsumer consumer)
        {
            if (element.GetProject().IsApplicableFor(this))
            {
                if (IsInvalid(element))
                {
                    SPC016401Highlighting errorHighlighting =
                        new SPC016401Highlighting(element);
                    consumer.ConsumeHighlighting(element.Header.GetDocumentRange(), errorHighlighting);
                }
            }
        }

        public static bool IsInvalid(IXmlTag element)
        {
            return element.Header.ContainerName == "properties" && !HasTitle(element);
        }

        private static bool HasTitle(IXmlTag element)
        {
            return
                element.GetNestedTags<IXmlTag>("property")
                    .Any(t => t.CheckAttributeValue("name", new[] {"Title"}, true));
        }
    }

    [ConfigurableSeverityHighlighting(CheckId, XmlLanguage.Name, OverlapResolve = OverlapResolveKind.NONE,
        ShowToolTipInStatusBar = true)]
    public class SPC016401Highlighting : XmlErrorHighlighting
    {
        public const string CheckId = "SPC016401";
        public const string Message = "Declare property 'Title' in WebParts";
        
        public IXmlTag Element { get; private set; }

        public SPC016401Highlighting(IXmlTag element) :
            base(String.Format("{0}: {1}", CheckId, Message))
        {
            Element = element;
        }

        public override bool IsValid()
        {
            return this.Element.IsValid();
        }
    }
    
}
